<?php

namespace app\api\controller;

use app\admin\model\Idea;
use app\admin\model\OrderGoods;
use app\common\controller\Api;
use app\admin\model\Banner;
//use app\common\library\token\driver\Redis;
use app\common\model\Area;
use app\common\model\GoodsDonate;
use app\common\model\GoodsDonateLeaveWord;
use app\common\model\Message;
use app\common\model\ShopMoneyLog;
use app\common\model\User;
use app\common\model\Order;
use fast\Random;
use think\Db;
use think\cache\driver\Redis;
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
//        $this->jie();
    }

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }
    /*
     * banner 列表
     * */
    public function bannerList(){
        $where['status']=1;
        $type = input('type',1);
        $where['status']=$type;
        $list = Banner::where($where)
            ->field('id,image,status,title,type,operater,jump_type,jump_value,createtime,updatetime,deletetime,goods_type,content')
            ->whereNull('deletetime')
            ->select();
        foreach ($list as $k=>$v){
            if($v['jump_type']==5){
                $list[$k]['jump_value']=$v['content'];
            }
        }
        $this->success('成功',$list);
    }

    /*
    * banner 详情
    * */
    public function bannerInfo(){
        $where['status']=1;
        $id = input('id');
        $where['id']=$id;
        $list = Banner::where($where)->whereNull('deletetime')->find();
        if($list['jump_type']==5){
            $list['jump_value']=$list['content'];
        }
        $this->success('成功',$list);
    }
    /**
     * 地址库
     * */
    public function areaList(){
        $id = input('id/d',0);
        $list = Area::getNextCityList($id);
        $this->success('请求成功!', ['list' => $list]);
    }

    /**
     * app地址库
     * */
    public function appareaList(){
        $redis = new Redis();
        $redis = $redis->handler();

        $list = $redis->get('area');

//        dd($list);
//        if(!$list){
            $id = input('id/d',0);
            $field = 'id,name,pid';
            $list = Area::getNextCityList($id,$field);
            foreach ($list as $k=>$v){
                $v['id'] =(string)$v['id'];
                $v['list'] = Area::getNextCityList($v['id'],$field);
                foreach ($v['list'] as $kk=>$vv){
                    $vv['id'] =(string)$vv['id'];
                    $vv['areaList'] = Area::getNextCityList($vv['id'],$field);
                    foreach ($vv['areaList'] as $kkk=>$vvv){
                        $vvv['id'] =(string)$vvv['id'];
                    }
                }
            }
            $list = json_encode($list);
//            dd($list);
            $redis->set('area',$list);
//        }
        $list = json_decode($list);
        $this->success('请求成功!',  $list);
    }
//-------------------------------------------------------------
// 消息
//-------------------------------------------------------------
    /**
     * 消息列表
     * */
    public function messageList(){
        $user_id = $this->auth->id;
//        $ids = '0';
//        if($user_id) $ids = $ids.','.$user_id;
//        $message = Message::order('id desc')->buildSql();
//        $list = Db::table($message.'a')
//            ->field('id,user_id,title,status')
//            ->where('user_id','in',$ids)
//            ->group('status')
//            ->paginate();
        $field='id,user_id,title,status';
        $list['status0'] = Message::where(['user_id'=>0])
            ->field($field)
            ->order('id desc')
            ->find();
        $list['status1'] = Message::where(['user_id'=>$user_id])
            ->field($field)
            ->order('id desc')
            ->find();
//
        $GoodsDonateLeaveWord = GoodsDonateLeaveWord::whereOr(['user_id'=>$user_id,'goods_user_id'=>$user_id])
            ->order('id desc')
            ->find();
        if(!empty($GoodsDonateLeaveWord)){
            $list['status2']['title'] = '收到一条留言';
        }
//        $list['status2'] = GoodsDonateLeaveWord::whereOr(['user_id'=>$user_id,'goods_user_id'=>$user_id])
//            ->order('id desc')
//            ->find();
        $this->success('成功',$list);
    }
    /**
     * 消息列表
     * 公告列表/物流列表
     * */
    public function messageInfoList(){
        $user_id = $this->auth->id;
        $type    = $this->request->param('type',0);//0 公告 1 交易
        if($type==0){
            $user_id=0;
        }
        $list = Message::where('user_id',$user_id)
            ->field('id,user_id,title,status,desc,createtime,image,type,order_id')
            ->order('id desc')
            ->paginate();
        foreach ($list as $k=>$v){
            $v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
            if($v['status']==1){
                if(!empty($v['order_id'])){
                    $Order = Order::getInfo($v['order_id']);
                    $v['logistic_num'] = $Order['logistic_num'];
                }
            }
        }
        $this->success('成功',$list);
    }
    /**
     * 消息详情
     * */
    public function messageInfo(){
        $id = $this->request->param('id');
        $list = Message::where('id',$id)
            ->order('id desc')
            ->find();
        $list['createtime'] = date('Y-m-d H:i:s',$list['createtime']);
        $this->success('成功',$list);
    }
    /*
     * 闲置留言
     * */
    public function messageGoodsDonate(){
        $user_id = $this->auth->id;
        $where['goods_donate_leave_word.user_id'] = $user_id;
        $where['goods_donate_leave_word.goods_user_id'] = $user_id;
        $list = GoodsDonateLeaveWord::whereOr($where)
            ->with(['goods','user'])
            ->order('id desc')
            ->paginate()
            ->toArray();
        $rs =[];
        foreach ($list['data'] as $k=>$v){
//            $v->getRelation('goods')->visible(['thumbnailimage','id']);
//            $v->getRelation('user')->visible(['nickname','id']);
            $v['createtime'] = datetime($v['createtime']);
            $v['content'] = $v['user']['nickname']."在您发布的闲置中留了一条言";
            //0 评论 否则回复
            if(empty($v['pid']) && $v['goods_user_id'] != $user_id){
                unset($v);
            }

            if(!empty($v)){
                $goods['id'] = $v['goods']['id'];
                $goods['thumbnailimage'] = $v['goods']['thumbnailimage'];
                unset($v['user']);
                unset($v['goods']);
                $v['goods'] = $goods;
                $rs[]=$v;
            }
        }
        $list['data']=$rs;
        $this->success('成功',$list);
    }
//----------------------------------------------------------------
// 意见反馈
//----------------------------------------------------------------
    /**
     * 意见反馈
     * */
    public function addOpinion() {
        $content = input('content');
        $image = input('image');
        $type = input('type', 1);
        $user_id = $this->auth->id;
        if (!$content || !$image) {
            $this->error('请完善信息');
        }
        $data['content'] = $content;
        $data['image'] = $image;
        $data['user_id'] = $user_id;
        $data['type'] = $type;
        $data['type'] = $type;
        Idea::create($data);
        $this->success('添加成功', []);
    }
    /**
     * 协议
     * type 1 商家入住协议 2 用户注册协议 3 关于我们协议 4 用户隐私协议 5帮助中心 6 操作指南
     * */
    public function deal(){
        $type = input('type',1);
        $info = Db::name('set_text')->where('id',1)->find();
        switch ($type){
            case 1:
                $info = $info['text1'];
                break;
            case 2:
                $info = $info['text2'];
                break;
            case 3:
                $info = $info['text3'];
                break;
            case 4:
                $info = $info['text4'];
                break;
            case 5:
                $info = $info['text5'];
                break;
            case 6:
                $info = $info['text6'];
                break;
        }
        $this->success('添加成功', $info);
    }

//---------------------------------------------------------------------
// 第三方登陆
//---------------------------------------------------------------------

    /**
     * 第三方登陆
     * */
    //app - 支付宝登陆
    public function alilogin(){
        $time = time();
        $appId = config('alipay.app_id');

        $url = "apiname=com.alipay.account.auth&method=alipay.open.auth.sdk.code.get&app_id={$appId}&app_name=mc&biz_type=openservice&pid=2088931189733781&product_id=APP_FAST_LOGIN&scope=kuaijie&target_id={$time}&auth_type=AUTHACCOUNT&sign_type=RSA2&sign";

        $this->success('成功',$url);
    }


    /**
     * pc端调起支付宝登陆
     * */
    public function ali(){
        $appId=config('alipay.app_id');
        $notify = urlencode("https://fubaoweb.191292.net/#/login/zfb");
        $url = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id={$appId}&scope=auth_user&state=init&redirect_uri={$notify}";
        $this->success('成功',$url);
    }

    /**
     * pc调起微信登陆
     * */
    public function wechat(){
        $notify = urlEncode("http://fubaoweb.191292.net/#/loginwx");
        $url = "https://open.weixin.qq.com/connect/qrconnect?appid=".config('wetch.app_id')."&redirect_uri={$notify}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirec";
        $this->success('成功',$url);
    }

    //根据code 获取微信信息-pc
    public function wechat2(){
        $code = input('code');
//        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={config('wetch.app_id')}&secret={config('wetch.app_key')}&code={$code}&grant_type=authorization_code";
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".config('wetch.app_id')."&secret=".config('wetch.app_key')."&code=".$code."&grant_type=authorization_code";
        $data = getUrl($url);
        $data = json_decode($data,true);
        $this->success('成功',$data);
    }

    //根据code 获取微信信息-小程序
    public function wechat1(){
        $code = input('code');
//        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".config('wetch.miniapp_id')."&secret=".config('wetch.key')."&js_code=".$code."&grant_type=authorization_code";
        $openid = getOpenid($code);
        if(empty($openid)){
            $this->error('授权失败');
        }
        $where['openid']=$openid;
        $user = User::where($where)->find();
        $type=1;
        if(!empty($user)){
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        }else{
            //不存在
            $ret = $this->auth->register($openid, Random::alnum(), '', '', ['openid'=>$openid]);
            $type=1;
        }
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo(),'type'=>$type];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /*
     * 第三方登陆
     * */
    public function loginThree(){
        $uid = input('uid');
        //1 支付宝 2 微信openid  3 苹果 4 微信unionid 5 qq 登陆
        $type = input('type',1);
        if($uid=='false'|| $uid == null){
            $this->error('失败');
        }
        switch ($type){
            case 1:
                $feild = 'aliid';
                break;
            case 2:
                $feild = 'openid';
                break;
            case 3:
                $feild = 'iosid';
                break;
            case 4:
                $feild = 'unionid';
                break;
            case 5:
                $feild = 'qqid';
                break;
        }
        $where[$feild]=$uid;
        $user = User::where($where)->find();

//        $type 0 未注册 1 未绑定手机号 2 未实名 3 正常登陆
        if(!empty($user)){
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
//            dd($ret);
            if(!$user['mobile']){
                $type=1;
            }elseif (!$user['id_card']){
                $type=2;
            }else{
                $type=3;
            }
        }else{
            //不存在
            $ret = $this->auth->register($uid, Random::alnum(), '', '', [$feild=>$uid]);
//            dd($ret);
            $type=1;
        }
//        dd($this->auth->user_type);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo(),'type'=>$type];
            $this->success(__('成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }



    public function share(){
        //1 微信小程序 2 朋友圈 3 qq 4 qq空间
        $type = $this->request->param('type',1);
        switch ($type){
            case 1:
                $info = 'http://www.babidu.com';
                break;
            case 2:
                $info = 'http://www.babidu.com';
                break;
            case 3:
                $info['url'] = 'http://www.babidu.com';
                break;
            case 4:
                $info['url'] = 'http://www.babidu.com';
                break;
        }

        $this->success('成功',$info);
    }

    /**
     * 协议
     * type 1 商家入住协议 2 用户注册协议 3 关于我们协议 4 用户隐私协议 5帮助中心 6 操作指南
     * */
    public function deal4(){
        $type = input('type',4);
        $info = Db::name('set_text')->where('id',1)->find();
        switch ($type){
            case 1:
                $info = $info['text1'];
                break;
            case 2:
                $info = $info['text2'];
                break;
            case 3:
                $info = $info['text3'];
                break;
            case 4:
                $info = $info['text4'];
                break;
            case 5:
                $info = $info['text5'];
                break;
            case 6:
                $info = $info['text6'];
                break;
        }
        return $info;
//        $this->success('添加成功', $info);
    }

    /*
     * pc qq获取code
     * */
    public function qqcode(){
        $redirect_uri =URLEncode("http://fubaoshop.fubaowenhua.com/#/qqlogin");
        $url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101926550&redirect_uri=".$redirect_uri."state=qqcode";
        $data = file_get_contents($url);
        return $data;
//        $this->success('成功',$data);
    }
    /*
     * 获取qq用户信息
     * */
    public function qq(){
        $access_token = $this->request->param('access_token');
        $url="https://graph.qq.com/oauth2.0/me?access_token=".$access_token."&fmt=json";
        $data = file_get_contents($url);
        $info = json_decode($data);
//        dd($info);
        $this->success('成功',$info);
    }

    /*
     * 小程序获取.getAccessToken
     * */
    public function getAccessToken($desc=''){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".config('wetch.miniapp_id')."&secret=".config('wetch.miniapp_key');
        $data = file_get_contents($url);
        $info = json_decode($data);
        $urll ="https://api.weixin.qq.com/wxa/msg_sec_check?access_token=".$info->access_token;
        $da['content'] = $desc;
        $da = json_encode($da, JSON_UNESCAPED_UNICODE);
        $datal = curl_post($urll,$da);
        $infol = json_decode($datal);
        return $infol->errcode;
    }


    //定时任务
    public function ji_auto(){
        $this->xiajia();//商品下架
        $this->cancel();//取消支付
        $this->jie();//商家结算
        $this->querenshuhuo();//确认收货
    }

    /*
     * 确认收货
     * */
    public function querenshuhuo(){
        $set = get_set();
        $where['status']=['<>',4];
//        $where['user_id']=16;
//        $where['id']=143;
        $time = time()+ $set['affirm'] * 60*60*24 ;
        $list = Order::whereTime('sendtime','>',$time)
            ->where($where)
            ->select();
        foreach ($list as $k=>$v){
            $v->status=4;
            $v->save();
        }
//        dd($list);
    }

    /**
     * 商家结算
     * */
    public function jie(){
        $where['status'] = 4;
        $where['type']   = 0;
        $where['is_jie']=0;
        $list = Order::where($where)
            ->whereTime('createtime','month')
            ->select();
//        dd($list);
        foreach ($list as $k=>$v){
            $info  = ShopMoneyLog::getAdd($v);
            $v->is_jie=1;
            $v->save();
        }
    }

    /*
     * 订单取消
     * */
    public function cancel(){
        $set = get_set();
        $where['status']=1;
        $where['type']=1;
//        $where['user_id']=16;
//        $where['id']=143;
        $time = time()- $set['cancel'] * 60 ;
//        dd($time);
        $list = Order::whereTime('createtime','<',$time)
            ->where($where)
//            ->fetchSql()
            ->select();
//        dd($list);
        foreach ($list as $k=>$v){
            $v->status=7;
            $v->canceltime=time();
            $v->save();
            $OrderGoods = OrderGoods::where(['order_id'=>$v['id']])->select();
//            dd($OrderGoods);
            foreach ($OrderGoods as $kk=>$vv){
                GoodsDonate::where('id','=',$vv['goods_id'])->update(['state'=>1]);
            }
        }
    }
    /*
     * 自动下架
     * */
    public function xiajia(){
        $set =get_set();
        $set['xiajia'];
        $where['state']=1;
//        $where['type']=1;
        $time = time()- $set['xiajia'] * 60 ;
        $list = GoodsDonate::whereTime('updatetime','<',$time)
//            ->fetchSql()
            ->where($where)
            ->select();
//        dd($list);
        foreach ($list as $k=>$v){
            $v->state =0;
            $v->save();
        }
    }


}
